import { useImperativeHandle, useState } from 'react';
import { Modal, Form, Input, Upload } from "antd";
import storage from '@/utils/storage'
import { message } from '@/utils/AntdGlobal';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {
    RcFile,
    UploadChangeParam,
    UploadFile,
    UploadProps
} from 'antd/es/upload';
import { IAction, IModalProps } from '@/type/model'
import { User } from '@/type/index'
import FormItem from 'antd/es/form/FormItem';
const CreateUser = (props: IModalProps) => {
    const [form] = Form.useForm();
    const [img, setImg] = useState('');
    const [loading, setLoading] = useState(false);

    const [visible, setVisible] = useState(false);//弹框的显示隐藏
    const [action, setAction] = useState<IAction>('create');
    // 暴漏子组件的open方法
    useImperativeHandle(props.myRef, () => {
        return {
            open
        }
    })
    // 调用弹框显示方法
    const open = (type: IAction, data?: User.UserItem) => {
        setVisible(true);
        setAction(type);
        if (type === 'edit' && data) {
            console.log(data);
            form.setFieldsValue(data);
        }
    }

    const handleSubmit = async () => {
        const valide = await form.validateFields();
        if (valide) {
            // 验证通过
            // 参数
            // const params = {
            //     ...form.getFieldValue(),
            //     userImg:img
            // }

            if (action === 'create') {
                message.success("创建成功");
                handleCancel();
                props.update();
            }
            if (action === 'edit') {

            }
            if (action === 'delete') {

            }
        }
    }
    const handleCancel = () => {
        form.resetFields();
        setImg('');//清空头像
        setVisible(false);
    }
    type FieldType = {
        userName?: string;
        userEmail?: string;
        dept?: string;
    };


    // 上传之前
    const beforeUpload = (fill: RcFile) => {
        const isJpgOrPng = fill.type === 'image/jpeg' || fill.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('你只能上传JPG/PNG格式的图片!');
        }
        const isLt2M = fill.size / 1024 / 1024 < 0.5;
        console.log(fill.size / 1024 / 1024);
        if (!isLt2M) {
            message.error('上传图片必须小于500k');
        }
        return isJpgOrPng && isLt2M;
    };
    // 上传后图片处理
    const handleChange: UploadProps['onChange'] = (
        info: UploadChangeParam<UploadFile>
    ) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
        }
        if (info.file.status === 'done') {
            setLoading(false);
            const { code, data, msg } = info.file.response;
            if (code === 0) {
                setImg(data.file);
            } else {
                message.error(msg);
            }
        } else if (info.file.status === 'error') {
            message.error('服务器异常，请稍后重试！');
        }
    };
    return (
        <Modal
            title={action === 'create' ? '创建用户' : '编辑用户'}
            width={800}
            open={visible}
            onOk={handleSubmit}
            onCancel={handleCancel}
        >
            <Form
                form={form}
                labelCol={{ span: 4 }}
                labelAlign="right"
            >
                <FormItem name="userId" hidden>
                    <Input></Input>
                </FormItem>
                <Form.Item<FieldType>
                    label="用户名称"
                    name="userName"
                    rules={[{ required: true, message: '请输入用户名称' },{min:5,max:10,message:'用户名称长度为5-10'}]}
                >
                    <Input />
                </Form.Item>

                <Form.Item<FieldType>
                    label="用户邮箱"
                    name="userEmail"
                    // {pattern:/1[1-9]\d{9}/',message:手机号必须为1开头得11位数字'}
                    // {pattern:/^\w+@mars.com$/,message:'邮箱结尾必须以@mars.com结尾'}
                    rules={[{ required: true, message: '请输入邮箱',type:'email' },{pattern:/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,message:'邮箱格式不正确'}]}
                >
                    <Input disabled={action === 'edit'} />
                </Form.Item>
                <Form.Item<FieldType>
                    label="部门"
                    name="dept"
                    rules={[{ required: true, message: '请输入部门' }]}
                >
                    <Input />
                </Form.Item>

                <Form.Item label='用户头像'>
                    <Upload
                        listType='picture-circle'
                        showUploadList={false}
                        headers={{
                            Authorization: `Bearer ${storage.get('token')} `,
                            icode: '7888DCA69B8C1D60'
                        }}
                        action='/api/users/upload'
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                    >
                        {img ? (
                            <img src={img} alt='头像' style={{ width: '100%', borderRadius: '100%' }}></img>
                        ) : (
                            <div>
                                {loading ? (
                                    <LoadingOutlined></LoadingOutlined>
                                ) : (
                                    <PlusOutlined></PlusOutlined>
                                )}
                                <div style={{ marginTop: 5 }}>上传头像</div>
                            </div>
                        )}
                    </Upload>
                </Form.Item>
            </Form>
        </Modal >
    )
}

export default CreateUser